<template>
  <div class="formBox">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-row class="title">房源信息</el-row>
      <el-form-item label="楼盘名称：" prop="buildingName" ref="buildingName">
        <el-row>
          <el-col :span="8">
            <el-autocomplete
              class="inline-input"
              v-model="ruleForm.buildingName"
              :fetch-suggestions="querySearch"
              placeholder="请输入小区名"
              :trigger-on-focus="false"
              @select="handleSelect"
            ></el-autocomplete>
          </el-col>
          <!-- <el-col :span="3" :offset="number">
            <el-button type="primary" icon="el-icon-search">搜索</el-button>
          </el-col> -->
        </el-row>
      </el-form-item>
      <el-form-item
        label="楼盘地址："
        prop="buildingAddress"
        ref="buildingAddress"
      >
        <el-row>
          <el-col :span="10">
            <el-input
              v-model="ruleForm.buildingAddress"
              placeholder="请输入小区地址"
              ><i slot="prefix" class="el-icon-location-outline"></i
            ></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="楼栋：" required>
        <el-row>
          <el-col :span="2">
            <el-form-item prop="buildingNum" ref="buildingNum">
              <el-input v-model="ruleForm.buildingNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1" center>
            <div class="text-center">楼栋</div>
          </el-col>
          <el-col :span="2">
            <el-form-item prop="buildingUnit" ref="buildingUnit">
              <el-input v-model="ruleForm.buildingUnit"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <div class="text-center">单元</div>
          </el-col>
          <el-col :span="2">
            <el-form-item prop="houseNum" ref="houseNum">
              <el-input v-model="ruleForm.houseNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <div class="text-center">门牌号</div>
          </el-col>
          <el-col :span="15"></el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        label="房源编号："
        prop="houseSerialNumber"
        ref="houseSerialNumber"
      >
        <el-row>
          <el-col :span="10">
            <el-input
              v-model="ruleForm.houseSerialNumber"
              disabled
              :placeholder="ruleForm.houseSerialNumber"
            ></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="租金：" prop="rent" ref="rent">
        <el-row>
          <el-col :span="2">
            <el-input v-model="ruleForm.rent" maxlength="8"></el-input>
          </el-col>
          <el-col :span="1"><div class="text-center">元/月</div></el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="支付方式：" prop="payment" ref="payment">
        <el-select v-model="ruleForm.payment" placeholder="请选择支付方式">
          <el-option
            :label="item.name"
            :value="item.name"
            v-for="item in paymentAll"
            :key="item.id"
          ></el-option>
          <!-- <el-option label="押一付三" value="threeMonth"></el-option>
          <el-option label="押一付半年" value="halfYear"></el-option>
          <el-option label="押一付一年" value="fullYear"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="租赁方式：" prop="lease">
        <el-select v-model="ruleForm.lease" placeholder="请选择租赁方式">
          <el-option
            :label="item.name"
            :value="item.name"
            v-for="item in leaseAll"
            :key="item.id"
          ></el-option>
          <!-- <el-option label="合租" value="half"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="户型：" required>
        <el-row>
          <el-col :span="1">
            <el-form-item prop="room">
              <el-input v-model="ruleForm.room"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1" center>
            <div class="text-center">室</div>
          </el-col>
          <el-col :span="1">
            <el-form-item prop="hall">
              <el-input v-model="ruleForm.hall"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <div class="text-center">厅</div>
          </el-col>
          <el-col :span="1">
            <el-form-item prop="toilet">
              <el-input v-model="ruleForm.toilet"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <div class="text-center">卫</div>
          </el-col>
          <el-col :span="1">
            <el-form-item prop="kitchen">
              <el-input v-model="ruleForm.kitchen"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <div class="text-center">厨</div>
          </el-col>
          <el-col :span="1">
            <el-form-item prop="balcony">
              <el-input v-model="ruleForm.balcony"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <div class="text-center">阳台</div>
          </el-col>
          <el-col :span="14"></el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="建筑面积：" prop="constructionArea">
        <el-row>
          <el-col :span="2">
            <el-input v-model="ruleForm.constructionArea"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="使用面积：" prop="usingArea">
        <el-row>
          <el-col :span="2">
            <el-input v-model="ruleForm.usingArea"></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="建筑年代：" prop="buildingAge">
        <el-row>
          <el-col :span="2">
            <el-input v-model="ruleForm.buildingAge"></el-input>
          </el-col>
          <el-col :span="1"><div class="text-center">年</div></el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="楼层：" required>
        <el-row>
          <el-col :span="2">
            <el-form-item prop="floor">
              <el-input v-model="ruleForm.floor"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1" center>
            <div class="text-center">/</div>
          </el-col>
          <el-col :span="2">
            <el-form-item prop="totalFloor">
              <el-input
                v-model="ruleForm.totalFloor"
                placeholder="总高"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="21"></el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="朝向：" prop="toward">
        <el-select v-model="ruleForm.toward" placeholder="请选择朝向">
          <el-option
            :label="item.name"
            :value="item.name"
            v-for="item in towardAll"
            :key="item.id"
          ></el-option>
          <!-- <el-option label="东南" value="es"></el-option>
          <el-option label="南" value="s"></el-option>
          <el-option label="西南" value="ws"></el-option>
          <el-option label="西" value="w"></el-option>
          <el-option label="西北" value="wn"></el-option>
          <el-option label="北" value="n"></el-option>
          <el-option label="东北" value="en"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="装修：" prop="decorate">
        <el-select v-model="ruleForm.decorate" placeholder="请选择装修">
          <el-option
            :label="item.name"
            :value="item.name"
            v-for="item in decorateAll"
            :key="item.id"
          ></el-option>
          <!-- <el-option label="简装修" value="simple"></el-option>
          <el-option label="精装修" value="refined"></el-option> -->
        </el-select>
      </el-form-item>
      <el-form-item label="配套设施：" prop="facilityIds" ref="facilityIds">
        <el-checkbox-group v-model="ruleForm.facilityIds">
          <el-checkbox
            :label="item.name"
            name="facilities"
            v-for="item in facilityAll"
            :key="item.id"
          ></el-checkbox>
          <!-- <el-checkbox label="电" name="facilities"></el-checkbox>
          <el-checkbox label="煤气/天然气" name="facilities"></el-checkbox>
          <el-checkbox label="暖气" name="facilities"></el-checkbox>
          <el-checkbox label="有线电视" name="facilities"></el-checkbox>
          <el-checkbox label="宽带" name="facilities"></el-checkbox>
          <el-checkbox label="电梯" name="facilities"></el-checkbox>
          <el-checkbox label="车位/车库" name="facilities"></el-checkbox>
          <el-checkbox label="储藏室/地下室" name="facilities"></el-checkbox> -->
        </el-checkbox-group>
      </el-form-item>
      <el-row class="title">图片信息</el-row>
      <el-form-item label="房源描述：" prop="propertyDescription">
        <el-row>
          <el-col :span="10">
            <el-input
              type="textarea"
              v-model="ruleForm.propertyDescription"
              placeholder="请输入备注"
              :show-word-limit="true"
              :autosize="{ minRows: 4, maxRows: 8 }"
            ></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="上传室内图：" prop="picture">
        <el-upload
          action=""
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-error="uploadError"
          :drag="dragBool"
          :multiple="dragBool"
          :limit="limitMax"
          accept="image/*"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-row class="title">出租信息</el-row>
      <el-form-item label="业主：" required>
        <el-row>
          <el-col :span="2">
            <el-form-item prop="owner">
              <el-input
                v-model="ruleForm.owner"
                placeholder="姓名"
                maxlength="10"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3" :offset="number">
            <el-form-item prop="phone">
              <el-input
                v-model="ruleForm.phone"
                placeholder="电话"
                maxlength="11"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="看房时间：" prop="checkingTime">
        <el-row>
          <el-col :span="4">
            <!-- <el-input v-model="ruleForm.checkingTime"></el-input> -->
            <el-date-picker
              v-model="ruleForm.checkingTime"
              type="datetime"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="物业费：" prop="propertyFee">
        <el-row>
          <el-col :span="2">
            <el-input v-model="ruleForm.propertyFee" maxlength="10"></el-input>
          </el-col>
          <el-col :span="2">
            <div class="text-center">元/平</div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button style="width:auto !important" type="primary" @click="submitForm('ruleForm')"
          >确认添加</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /* 查看大图的地址和显示隐藏 */
      dialogImageUrl: "",
      dialogVisible: false,
      /* 支持拖拽文件上传 */
      dragBool: true,
      /* 最多上传的图片数 */
      limitMax: 10,
      number: 1,
      restaurants: [],
      ruleForm: {
        buildingName: "",
        buildingAddress: "",
        buildingNum: "",
        buildingUnit: "",
        houseNum: "",
        houseSerialNumber: "",
        rent: "",
        payment: "",
        lease: "",
        room: "",
        hall: "",
        toilet: "",
        kitchen: "",
        balcony: "",
        constructionArea: "",
        usingArea: "",
        buildingAge: "",

        floor: "",
        totalFloor: "",
        toward: "",
        decorate: "",
        /* 设备信息 */
        facilityIds: [],
        propertyDescription: "",
        /* 图片地址 */
        indoorFigure: "",
        owner: "",
        phone: "",
        checkingTime: "",
        propertyFee: "",
        /* 房源详情外键 */
        detailId: 0,
      },
      /* 准备上传的文件列表 */
      fileList: [],
      /* 连接后存储上传的图片链接 */
      fileListUrl: [],
      /* 传给后端的数据 */
      subForm: {},
      /* 输入框校验规则 */
      rules: {
        buildingName: [
          { required: true, message: "请输入楼盘名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "change",
          },
        ],
        buildingAddress: [
          { required: true, message: "请输入楼盘地址", trigger: "blur" },
          { min: 1, max: 20, message: "长度少于20个字符", trigger: "blur" },
        ],
        buildingNum: [
          { required: true, message: "请输入楼栋", trigger: "blur" },
          { min: 1, max: 5, message: "长度少于5个字符", trigger: "blur" },
        ],
        buildingUnit: [
          { required: true, message: "请输入单元", trigger: "blur" },
          { min: 1, max: 5, message: "长度少于5个字符", trigger: "blur" },
        ],
        houseNum: [
          { required: true, message: "请输入门牌号", trigger: "blur" },
          { max: 10, message: "长度少于10个字符", trigger: "blur" },
        ],
        rent: [
          { required: true, message: "请输入租金", trigger: "blur" },
          { max: 8, message: "长度少于8个字符", trigger: "blur" },
        ],
        payment: [
          { required: true, message: "请选择支付方式", trigger: "change" },
        ],
        lease: [
          { required: true, message: "请选择租赁方式", trigger: "change" },
        ],
        room: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 2, message: "长度少于2个字符", trigger: "blur" },
        ],
        hall: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 2, message: "长度少于2个字符", trigger: "blur" },
        ],
        toilet: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 2, message: "长度少于2个字符", trigger: "blur" },
        ],
        kitchen: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 2, message: "长度少于2个字符", trigger: "blur" },
        ],
        balcony: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 2, message: "长度少于2个字符", trigger: "blur" },
        ],
        floor: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 2, message: "长度少于2个字符", trigger: "blur" },
        ],
        totalFloor: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 2, message: "长度少于2个字符", trigger: "blur" },
        ],
        owner: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 1, max: 10, message: "长度少于10个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入", trigger: "blur" },
          { min: 11, max: 11, message: "请输入正确手机号", trigger: "blur" },
        ],
        facilityIds: [
          {
            type: "array",
            required: true,
            message: "请至少选择一项配置",
            trigger: "change",
          },
        ],
      },
      /* 所有设施 */
      facilityAll: [],
      /* 支付方式 */
      paymentAll: [],
      /* 租赁方式 */
      leaseAll: [],
      /* 所有朝向 */
      towardAll: [],
      /* 所有装修 */
      decorateAll: [],
    };
  },
  methods: {
    /* 添加按钮 */
    submitForm(formName) {
      console.log(this.ruleForm);
      let time = this.getTime(this.ruleForm.checkingTime);
      console.log(time);
      this.$refs[formName].validate((valid, object) => {
        console.log(this.ruleForm);
        if (valid) {
          this.subForm = JSON.parse(JSON.stringify(this.ruleForm));
          let facilityChoice = [];
          /* 把设备信息转换成id字符串 */
          this.facilityAll.forEach((item) => {
            this.ruleForm.facilityIds.forEach((item2) => {
              if (item.name === item2) {
                facilityChoice.push(item.id);
              }
            });
          });
          this.subForm.facilityIds = facilityChoice.join(",");
          this.subForm.indoorFigure = this.fileListUrl.join(",");
          this.subForm.checkingTime = time;
          console.log(this.subForm);
          /* 添加房源接口 */
          this.$axios({
            url: "/houseInfo/insert",
            method: "post",
            data: this.subForm,
          }).then((res) => {
            console.log(res);
            if (res.code === 0) {
              this.$message({
                type: "success",
                message: "添加成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        } else {
          let split = "";
          for (let i in object) {
            let dom = this.$refs[i];
            // console.log(dom);
            if (Object.prototype.toString.call(dom) !== "[object Object]") {
              dom = dom[0];
              split = dom.prop;
              let index = split.indexOf(".");
              let last = split.lastIndexOf(".");
              this.activeName = Number(split.slice(index + 1, last));
              break;
            }
            // console.log(dom.$el);
            dom.$el.scrollIntoView({
              block: "start",
              behavior: "instant",
            });
            this.$message({
              type: "error",
              message: "输入信息有误!",
            });
            return false;
          }
          console.log("error submit!!");
          return false;
        }
      });
    },
    /* 时间拼接函数 */
    getTime(t) {
      if (t === "") {
        return "";
      } else {
        let time = new Date(t);
        let year = time.getFullYear();
        let month =
          time.getMonth() < 10 ? `0${time.getMonth() + 1}` : time.getMonth();
        let date = time.getDate() < 10 ? `0${time.getDate()}` : time.getDate();
        let hours =
          time.getHours() < 10 ? `0${time.getHours()}` : time.getHours();
        let minutes =
          time.getMinutes() < 10 ? `0${time.getMinutes()}` : time.getMinutes();
        let seconds =
          time.getSeconds() < 10 ? `0${time.getSeconds()}` : time.getSeconds();
        time = `${year}-${month}-${date}T${hours}:${minutes}:${seconds}Z`;
        return time;
      }
    },
    handleChange(file, fileList) {
      this.fileList = [];
      fileList.forEach((item) => {
        this.fileList.push(item.raw);
      });
      this.getFileListUrl();
      // console.log(this.fileList);
    },
    handleRemove(file, fileList) {
      this.fileList = [];
      fileList.forEach((item) => {
        this.fileList.push(item.raw);
      });
    },
    /* 获取所有上传文件产生的链接 */
    getFileListUrl() {
      this.fileListUrl = [];
      this.fileList.forEach((item) => {
        let formdata = new FormData();
        formdata.append("file", item);
        // console.log(formdata.get("file"));
        this.$axios({
          url: "/uploadImage",
          method: "POST",
          data: {
            image: formdata.get("file"),
          },
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }).then((res) => {
          // console.log(res);
          if (res.code === 0) {
            this.fileListUrl.push(res.data);
          }
        });
      });
      // console.log(this.fileListUrl);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$message({
        type: "success",
        message: "重置成功!",
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [
        { value: "红树湾", address: "长宁区新渔路144号" },
        { value: "南湖左岸", address: "爱情路520号1314弄" },
        {
          value: "警官公寓",
          address: "上海市长宁区淞虹路661号",
        },
        {
          value: "国信安",
          address: "上海市普陀区光复西路丹巴路",
        },
        {
          value: "无国界",
          address: "上海市长宁区仙霞西路88号",
        },
        { value: "欢乐颂", address: "上海市普陀区棕榈路" },
        { value: "龙湖世纪峰景", address: "元丰天山花园(东门) 双流路267号" },
        { value: "金科星耀天都", address: "上海市长宁区天山西路" },
        { value: "华润国际社区", address: "上海市长宁区通协路" },
        {
          value: "万科金润华府",
          address: "上海市长宁区新泾镇金钟路999号",
        },
        { value: "朝阳时代西锦", address: "长宁区仙霞西路88号" },
        {
          value: "佳兆业丽晶港",
          address:
            "上海市普陀区真北路818号",
        },
        {
          value: "德商华府天骄",
          address: "上海市金钟路633号",
        },
      ];
    },
    handleSelect(item) {
      this.ruleForm.buildingAddress = item.address;
      // console.log(item);
    },
    uploadError(err, file, fileList) {
      console.log("文件上传失败", err);
    },
    /* 获取所有设施信息 */
    getFacilityAll() {
      this.$axios({
        url: "/facility/findAll",
        method: "GET",
      }).then((res) => {
        // console.log(res);
        this.facilityAll = res.data;
      });
    },
  },
  mounted() {
    this.restaurants = this.loadAll();
  },
  created() {
    /* 拿所有设施信息 */
    this.getFacilityAll();
    this.ruleForm.houseSerialNumber = "123456";
    /* 装修 */
    this.$axios({
      url: "/configuration/findAllDecorate",
      method: "GET",
    }).then((res) => {
      // console.log(res);
      this.decorateAll = res.data;
    });
    /* 租赁方式 */
    this.$axios({
      url: "/configuration/findAllLease",
      method: "GET",
    }).then((res) => {
      // console.log(res);
      this.leaseAll = res.data;
    });
    /* 支付方式 */
    this.$axios({
      url: "/configuration/findAllPayment",
      method: "GET",
    }).then((res) => {
      // console.log(res);
      this.paymentAll = res.data;
    });
    /* 朝向 */
    this.$axios({
      url: "/configuration/findAllToward",
      method: "GET",
    }).then((res) => {
      // console.log(res);
      this.towardAll = res.data;
    });
  },
};
</script>

<style scoped>
.el-autocomplete {
  width: 100%;
}
.text-center {
  text-align: center;
}
.title {
  font-size: 20px;
  font-weight: 600;
  margin-top: 0;
  margin-bottom: 20px;
}
.formBox {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
}
</style>